﻿using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using Sapit.Attributes.Interfaces;

namespace Sapit.Unity.Attributes
{
    /// <summary>
    /// Apply this attribute to methods that should have a breaker switch applied to them.
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public class CircuitBreakerAttribute : HandlerAttribute, ICircuitBreaker
    {
        /// <summary>
        /// The maximum number of consecutive failed attempts to call the method
        /// </summary>
        public int MaxConsecutiveFailures { get; set; }
        /// <summary>
        /// The number of seconds to shortcircuit the method when the maximum number of consecutive failures is reached
        /// </summary>
        public int ShutOffPeriodSeconds { get; set; }
        /// <summary>
        /// Defines the behavior when the external dependency is switched off, return a default value or throw an exception
        /// </summary>
        public Behavior BehaviorWhenShutOff { get; set; }
        /// <summary>
        /// The value to return when the method is switched off
        /// </summary>
        public object ShutOffReturnValue { get; set; }

        public override ICallHandler CreateHandler(IUnityContainer container)
        {
            return new CircuitBreakerHandler();
        }
    }
}
